package com.zjff.myshop.admin.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.zjff.myshop.admin.pojo.form.AdminLoginForm;
import com.zjff.myshop.admin.pojo.vo.SysUserVO;
import com.zjff.myshop.admin.service.SysUserService;
import com.zjff.myshop.entity.SysUser;
import com.zjff.myshop.front.controller.UserController;
import com.zjff.myshop.front.pojo.vo.UserLoginVO;
import com.zjff.myshop.util.BeanUtils;
import com.zjff.myshop.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

@CrossOrigin
@RestController
@Api(value = "v1", tags = "81.后台管理系统-系统用户模块")
@RequestMapping("/admin/v1/sysUser")
public class AdminSysUserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Resource
    private SysUserService sysUserService;

    /**
     * 系统用户登录
     */
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "系统用户登录", notes = "返回用户id、token")
    @ApiImplicitParam(name = "form", value = "系统用户登录参数", dataType = "AdminLoginForm", required = true)
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody @Valid AdminLoginForm form) {
        SysUser sysUser = sysUserService.login(form.getName(), form.getPassword());
        logger.info("login api,name={},userId={}", form.getName(), sysUser.getId());
        //登录成功
        Integer userId = sysUser.getId();
        StpUtil.login(userId, "PC");//后台管理用户登录
        String token = StpUtil.getTokenInfo().getTokenValue();
        // Set<String> permissions=userService.getUserPermissions(userId);获取权限
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(sysUser, userLoginVO);
        userLoginVO.setToken(token);
        return Result.ok(userLoginVO);
    }

    /**
     * 系统用户登出
     */
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "系统用户登出", notes = "清除token")
    @SaCheckLogin
    @PostMapping("/logout")
    public Result logout() {
        StpUtil.logout();
        return Result.ok(); //登出成功
    }

    /**
     * 查询
     */
    @ApiOperationSupport(order = 30)
    @ApiOperation(value = "查询当前登录的系统用户详情信息", notes = "查询当前登录的系统用户详情信息")
    @SaCheckLogin
    @GetMapping("/selectDetailByMy")
    public Result<SysUserVO> selectDetailByMy() {
        Integer userId = StpUtil.getLoginIdAsInt();
        SysUser sysUser = sysUserService.selectByPrimaryKey(userId);
        if (sysUser == null) {
            return Result.error();
        }
        SysUserVO sysUserVO = new SysUserVO();
        BeanUtils.copyProperties(sysUser, sysUserVO);
        return Result.ok(sysUserVO);
    }
}
